package com.Maykk.Demo07;

/**
 * @ClassName: SellTickets
 * @Description: TODO 门票线程类
 * @Author: MaykkStar@163.com
 */
public class SellTickets implements Runnable {
    private static int tickets = 100;

    @Override
    public void run() {
        while (true) {
            if (this.tickets > 0) {
                sellTickets();
            } else {
                System.out.println("没票了");
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 同步方法
     */
    // public synchronized void sellTickets() {
    //     System.out.println(Thread.currentThread().getName() + "卖出了第" + this.tickets +"张票");
    //     tickets--;
    // }

    /**
     * 同步静态方法 - 两种
     */
    // public static synchronized void sellTickets() {
    //     System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets +"张票");
    //     tickets--;
    // }
    public static void sellTickets() {
        synchronized (SellTickets.class) { // 注意：此处使用反射获取当前类对象
            System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets + "张票");
            tickets--;
        }
    }
}
